// 发送请求
function http(url, callback, key, name) {
  wx.request({
    url: url,
    //（需大写）有效值：OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
    method: "GET",
    // header 中不能设置 Referer
    header: {
      "content-type": "json",
    },
    success: function (res) {
      typeof callback === "function" && callback(res.data, key, name);
    },
  });
}

const baseUrl = "http://192.168.1.167:29000/xcxApi/xcx";
// 封装Ajax
export function http1(url = "", options) {
  const { method = "GET", data = {}, header = {} } = options || {};
  return new Promise((resolve, reject) => {
    wx.request({
      url: baseUrl + url,
      data,
      method,
      header: Object.assign({}, header, {
        Authorization: wx.getStorageSync("token"),
      }),
      success(res) {
        resolve(res.data);
      },
      fail(err) {
        reject(err);
      },
    });
  });
}

// 获取星星类型
function getStarArr(star) {
  var arr = [];
  for (var i = 0; i < 5; i++) {
    if (i < star.substr(0, 1)) {
      arr.push(1);
    } else if (i == star.substr(0, 1)) {
      star.substr(1, 1) >= 5 ? arr.push(2) : arr.push(0);
    } else {
      arr.push(0);
    }
  }
  return arr;
}

// 演员字符串信息
function convertToString(casts) {
  var arr = [];
  for (var i = 0; i < casts.length; i++) {
    arr.push(casts[i]["name"]);
  }
  return arr.join(" / ");
}

// 演员数组信息
function convertToArr(casts) {
  var arr = [];
  for (var i in casts) {
    var obj = {
      actorImg: casts[i]["avatars"] ? casts[i]["avatars"]["large"] : "",
      actorName: casts[i]["name"],
    };
    arr.push(obj);
  }
  return arr;
}

function formatTime(date) {
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var day = date.getDate();

  var hour = date.getHours();
  var minute = date.getMinutes();
  var second = date.getSeconds();

  return (
    [year, month, day].map(formatNumber).join("/") +
    " " +
    [hour, minute, second].map(formatNumber).join(":")
  );
}

function formatNumber(n) {
  n = n.toString();
  return n[1] ? n : "0" + n;
}

let stacks = [];

function fetchAllPages() {
  let stack = getCurrentPages();
  // 第一个入栈
  stack.forEach((item) => {
    if (stacks.length === 0) {
      stacks = stack.concat();
    } else {
      for (let i = 0, _len = stacks.length; i < _len; i++) {
        let ele = stacks[i];
        if (ele.__route__ === item.__route__) {
          stacks[i] = item;
          break;
        } else {
          stacks.push(item);
          break;
        }
      }
    }
  });
  // }
  return stacks;
}

module.exports = {
  http: http,
  getStarArr: getStarArr,
  convertToString: convertToString,
  convertToArr: convertToArr,
};
